<?php
namespace app\controller;

use app\BaseController;
use app\model\Account;
use app\model\AccountValidator;
use think\exception\ValidateException;
use app\common\AssocObject;

class AccountController extends BaseController
{
    public function index()
    {
        $account = new Account();
        if($this->request->has("keyword")){
            $account->whereOr('username','like','%'.$this->request->param('keyword'));
        }
        $list = $account->order('id', 'desc')->paginate(3);
        return view('list',['list'=>$list]);
    }

    public function create(){
        return view('edit',['data'=>[],'valids'=>[]]);
    }

    public function add(){
        $data = $this->request->param();
        $valids = null;
        try {
            $valids = validate(AccountValidator::class)->batch(true)->check($data);
    
            if (true !== $valids) {
                // 验证失败 输出错误信息
                return view('edit',['data'=>$data,'valids'=>$valids]);
            } else {
                $account = new Account($data);
                if($account->save()) {
                    echo '新添成功';
                } else {
                    echo '新添失败';
                }
            }
        } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $view = view('edit',['data'=>$data,'valids'=>$e->getError()]);
                return $view;
        }
    }

    

    public function edit(){
        return 'edit view';
    }

    public function modify(){
        return 'modify view';
    }

    public function delete(){
        return 'delete view';
    }
}
